/**
 * @Author:  renyc
 * @Date: 2022年12月4日16:25:07
 */

import * as Cesium from "cesium/Cesium";
import * as echarts from 'echarts';


class GLMapCoordSystem {
   constructor(viewer, api) {
     this._viewer = viewer
     this._dimensions = ['lng', 'lat']
     this._mapOffset = [0, 0]
     this._api = api
   }
 
   setMapOffset(mapOffset) {
     this._mapOffset = mapOffset
     return this
   }
 
   getViewer() {
     return this._viewer
   }
 
   dataToPoint(data) {
     let result = []
     let cartesian3 = Cesium.Cartesian3.fromDegrees(data[0], data[1])
     if (!cartesian3) {
       return result
     }
     let up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
       cartesian3,
       new Cesium.Cartesian3()
     )
     let cd = this._viewer.camera.direction
     if (Cesium.Cartesian3.dot(up, cd) >= 0) {
       return result
     }     
     let coords = this._viewer.scene.cartesianToCanvasCoordinates(cartesian3)
     if (!coords) {
       return result
     }
     //console.log("[canvas coordinate]: " + (coords.x - this._mapOffset[0]) + " , " + (coords.y - this._mapOffset[1]));
     return [coords.x - this._mapOffset[0], coords.y - this._mapOffset[1]]
   }
 
   pointToData(point) {
     let ellipsoid = this._viewer.scene.globe.ellipsoid
     let cartesian3 = new Cesium.Cartesian3(
       point[0] + this._mapOffset[0],
       point[1] + this._mapOffset[1],
       0
     )
     let cartographic = ellipsoid.cartesianToCartographic(cartesian3)
     return [
       Cesium.Math.toDegrees(cartographic.longitude),
       Cesium.Math.toDegrees(cartographic.latitude)
     ]
   }
 
   getViewRect() {
     let api = this._api
     return new echarts.graphic.BoundingRect(
       0,
       0,
       api.getWidth(),
       api.getHeight()
     )
   }
 
   getRoamTransform() {
     return echarts.matrix.create()
   }
 
   get dimensions() {
     return this._dimensions
   }
 
   static get dimensions() {
     return ['lng', 'lat']
   }
 
   static create(ecModel, api) {
     let coordinateSys = undefined
     ecModel.eachComponent('GLMap', function(model) {
      /**
       * 这里需要一个全局cesium.viewer
       */
      coordinateSys = new GLMapCoordSystem(window.viewer, api)
       //coordinateSys = new GLMapCoordSystem(echarts.viewer, api)
       coordinateSys.setMapOffset(model.__mapOffset || [0, 0])
       model.coordinateSystem = coordinateSys
     })
     ecModel.eachSeries(function(model) {
       'GLMap' === model.get('coordinateSystem') &&
         (model.coordinateSystem = coordinateSys)
     })
   }
 }
 
 export default GLMapCoordSystem
 